import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../index.dart';
import '../page/activity_management_page.dart';
import '../page/activity_edit_page.dart';
import '../../../../../common/utils/toast_util.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/api/comment_api.dart';
import '../../../../../common/api/activity_api.dart';
import '../../../../../common/services/user_service.dart'; // 🔥 添加UserService导入
import '../../models/post_model.dart';
import '../../../../home/widgets/activity_detail_bottom_sheet.dart';
import '../comment/review_detail_bottom_sheet.dart';
import 'dart:developer' as developer;


class MyPublishTab extends StatefulWidget {
  const MyPublishTab({Key? key}) : super(key: key);

  @override
  _MyPublishTabState createState() => _MyPublishTabState();
}



class _MyPublishTabState extends State<MyPublishTab>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  


  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFD94841),
      child: Column(
        children: [
          SizedBox(height: MediaQuery.of(context).padding.top + 5),
          // 活动管理标题
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            child: Text(
              '活动管理',
              style: TextStyle(
                  color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
            ),
          ),
          // 活动管理列表 - 显示所有活动（与MyApplication2一致）
          GetBuilder<PlaysController>(
            builder: (controller) {
              // 动态计算高度：无活动时120，有活动时根据数量计算
              final double height = controller.myActivities.isEmpty 
                  ? 120.0 
                  : (controller.myActivities.length * 110.0 + 40.0).clamp(120.0, 250.0);
              
              return Container(
                height: height,
                child: SmartRefresher(
                  enablePullDown: true,
                  enablePullUp: false,
                  header: WaterDropHeader(
                    complete: const Text(
                      '刷新完成',
                      style: TextStyle(color: Colors.white70),
                    ),
                    refresh: const SizedBox(
                      width: 25.0,
                      height: 25.0,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.0,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    ),
                    waterDropColor: Colors.white,
                  ),
                  controller: controller.activityManagementRefreshController,
                  onRefresh: controller.onActivityManagementRefresh,
                  child: SingleChildScrollView(
                    child: _buildActivityManagementSection(controller),
                  ),
                ),
              );
            },
          ),
          TabBar(
            controller: _tabController,
            labelColor: Colors.white,
            unselectedLabelColor: Colors.white70,
            indicatorColor: Colors.white,
            indicatorSize: TabBarIndicatorSize.label,
            tabs: const [
              Tab(text: '历史活动'),
              Tab(text: '我的评论'),
              Tab(text: '我的参与'),
            ],
          ),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                GetBuilder<PlaysController>(
                  builder: (controller) {
                    return SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: false,
                      header: WaterDropHeader(
                        complete: const Text(
                          '刷新完成',
                          style: TextStyle(color: Colors.white70),
                        ),
                        refresh: const SizedBox(
                          width: 25.0,
                          height: 25.0,
                          child: CircularProgressIndicator(
                            strokeWidth: 2.0,
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          ),
                        ),
                        waterDropColor: Colors.white,
                      ),
                      controller: controller.myHistoryRefreshController,
                      onRefresh: controller.onMyHistoryRefresh,
                      child: controller.myEndedActivities.isEmpty
                          ? Container(
                              width: double.infinity,
                              height: 200,
                              child: const Center(
                                child: Text(
                                  '无',
                                  style: TextStyle(
                                    color: Colors.white70,
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            )
                          : ListView.builder(
                              padding: const EdgeInsets.only(top: 8, bottom: 8),
                              itemCount: controller.myEndedActivities.length,
                              itemBuilder: (context, index) {
                                final activity = controller.myEndedActivities[index];
                                return Card(
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                                  margin: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                                  // 🔥 修复：使用ActivityData显示历史活动详情
                                  child: InkWell(
                                    onTap: () => _showHistoricalActivityDetailFromActivityData(activity),
                                    borderRadius: BorderRadius.circular(12),
                                    child: Padding(
                                      padding: const EdgeInsets.all(12.0),
                                      child: Row(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                        ClipRRect(
                                          borderRadius: BorderRadius.circular(8.0),
                                          child: CachedNetworkImage(
                                            imageUrl: activity.activityImages.isNotEmpty ? activity.activityImages.first : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png',
                                            width: 80,
                                            height: 80,
                                            fit: BoxFit.cover,
                                            errorWidget: (context, url, error) {
                                              return Container(
                                                width: 80,
                                                height: 80,
                                                color: Colors.grey[300],
                                                child: const Icon(Icons.image_not_supported, size: 30),
                                              );
                                            },
                                          ),
                                        ),
                                        const SizedBox(width: 12),
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  Expanded(
                                                    child: Row(
                                                      mainAxisSize: MainAxisSize.min,
                                                      children: [
                                                        Expanded(
                                                          child: Text(
                                                            activity.activityTitle.isNotEmpty ? activity.activityTitle : '活动标题',
                                                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                                                            overflow: TextOverflow.ellipsis,
                                                          ),
                                                        ),
                                                        const SizedBox(width: 8),
                                                        Container(
                                                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                                          decoration: BoxDecoration(
                                                            color: Colors.red.shade100,
                                                            borderRadius: BorderRadius.circular(4),
                                                          ),
                                                          child: Text(
                                                            activity.activityType.isNotEmpty ? activity.activityType.first : 'AA',
                                                            style: const TextStyle(color: Colors.red, fontSize: 12),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                  Container(
                                                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                                    decoration: BoxDecoration(
                                                      color: Colors.grey.shade200,
                                                      borderRadius: BorderRadius.circular(8),
                                                    ),
                                                    child: Text('活动', style: TextStyle(color: Colors.grey.shade700, fontSize: 12)),
                                                  ),
                                                ],
                                              ),
                                              const SizedBox(height: 8),
                                              Text(
                                                activity.activityDetails.isNotEmpty ? activity.activityDetails : '活动详情',
                                                style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                              const SizedBox(height: 8),
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  RichText(
                                                    text: TextSpan(
                                                      style: DefaultTextStyle.of(context).style.copyWith(fontSize: 14),
                                                      children: <TextSpan>[
                                                        const TextSpan(text: '最终参与人数 '),
                                                        TextSpan(
                                                          text: '${activity.activityCurrentParticipants}',
                                                          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                  GestureDetector(
                                                    onTap: () => _deleteHistoricalActivityWithCorrectAPI(activity.activityId, index),
                                                    child: Container(
                                                      padding: const EdgeInsets.all(8.0),
                                                      child: Row(
                                                        mainAxisSize: MainAxisSize.min,
                                                        children: [
                                                          Icon(Icons.delete_outline, size: 16, color: Colors.grey.shade600),
                                                          const SizedBox(width: 4),
                                                          Text('删除', style: TextStyle(color: Colors.grey.shade600, fontSize: 12)),
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                    );
                  },
                ),
                // 我的评论列表
                Obx(() {
                  final controller = Get.find<PlaysController>();
                  return SmartRefresher(
                    enablePullDown: true,
                    enablePullUp: false,
                    header: WaterDropHeader(
                      complete: const Text(
                        '刷新完成',
                        style: TextStyle(color: Colors.white70),
                      ),
                      refresh: const SizedBox(
                        width: 25.0,
                        height: 25.0,
                        child: CircularProgressIndicator(
                          strokeWidth: 2.0,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      ),
                      waterDropColor: Colors.white,
                    ),
                    controller: controller.myCommentsRefreshController,
                    onRefresh: controller.onMyCommentsRefresh,
                    child: controller.isLoadingUserContent.value
                        ? const Center(
                            child: Padding(
                              padding: EdgeInsets.all(50.0),
                              child: CircularProgressIndicator(),
                            ),
                          )
                        : controller.myRealComments.isEmpty
                            ? Container(
                                width: double.infinity,
                                height: 200,
                                child: const Center(
                                  child: Text(
                                    '无',
                                    style: TextStyle(
                                      color: Colors.white70,
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ),
                              )
                            : ListView.builder(
                                padding: const EdgeInsets.only(top: 8, bottom: 8),
                                itemCount: controller.myRealComments.length,
                                itemBuilder: (context, index) {
                                  final comment = controller.myRealComments[index];
                                  return InkWell(
                                    onTap: () => _showCommentDetail(comment), // 🔥 添加点击事件，显示评论详情
                                    borderRadius: BorderRadius.circular(16),
                                    child: _buildRealCommentCard(comment),
                                  );
                                },
                              ),
                  );
                }),
                // 我的参与列表
                Obx(() {
                  final controller = Get.find<PlaysController>();
                  return SmartRefresher(
                    enablePullDown: true,
                    enablePullUp: false,
                    header: WaterDropHeader(
                      complete: const Text(
                        '刷新完成',
                        style: TextStyle(color: Colors.white70),
                      ),
                      refresh: const SizedBox(
                        width: 25.0,
                        height: 25.0,
                        child: CircularProgressIndicator(
                          strokeWidth: 2.0,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      ),
                      waterDropColor: Colors.white,
                    ),
                    controller: controller.myParticipationRefreshController,
                    onRefresh: controller.onMyParticipationRefresh,
                    child: controller.isLoadingUserContent.value
                        ? const Center(
                            child: Padding(
                              padding: EdgeInsets.all(50.0),
                              child: CircularProgressIndicator(),
                            ),
                          )
                        : controller.myParticipatedActivities.isEmpty
                            ? Container(
                                width: double.infinity,
                                height: 200,
                                child: const Center(
                                  child: Text(
                                    '无',
                                    style: TextStyle(
                                      color: Colors.white70,
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ),
                              )
                            : ListView.builder(
                                padding: const EdgeInsets.only(top: 8, bottom: 8),
                                itemCount: controller.myParticipatedActivities.length,
                                itemBuilder: (context, index) {
                                  final activity = controller.myParticipatedActivities[index];
                                  return InkWell(
                                    onTap: () => _showParticipatedActivityDetail(activity), // 🔥 添加点击事件，显示参与活动详情
                                    borderRadius: BorderRadius.circular(16),
                                    child: _buildRealParticipantActivityCard(activity),
                                  );
                                },
                              ),
                  );
                }),
              ],
            ),
          ),
        ],
      ),
    );
  }







  /// 构建活动管理区域（显示所有活动，与MyApplication2一致）
  Widget _buildActivityManagementSection(PlaysController controller) {
    // 获取所有管理的活动
    final managementActivities = controller.myActivities;
    
    // 如果没有活动数据，显示简洁的“无”提示
    if (managementActivities.isEmpty) {
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        child: Card(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Container(
            width: double.infinity,
            height: 100,
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Center(
              child: Text(
                '无',
                style: TextStyle(
                  color: Colors.black54,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ),
      );
    }
    
    // 显示所有管理的活动（与MyApplication2一致）
    return Column(
      children: managementActivities.map((activity) => 
        _buildSingleActivityManagementCard(activity, controller)
      ).toList(),
    );
  }
  
  /// 构建单个活动管理卡片（支持左滑删除）
  Widget _buildSingleActivityManagementCard(ActivityData activity, PlaysController controller) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
      child: Dismissible(
        key: Key('activity_${activity.activityId}'),
        direction: DismissDirection.endToStart, // 🔥 只允许从右向左滑动
        background: Container(
          decoration: BoxDecoration(
            color: Colors.red.shade600,
            borderRadius: BorderRadius.circular(12),
          ),
          alignment: Alignment.centerRight,
          padding: const EdgeInsets.only(right: 20),
          child: const Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.delete_forever,
                color: Colors.white,
                size: 32,
              ),
              SizedBox(height: 4),
              Text(
                '删除活动',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
        confirmDismiss: (direction) async {
          // 🔥 显示删除确认对话框
          return await _showDeleteActivityConfirmDialog(activity);
        },
        onDismissed: (direction) {
          // 🔥 执行删除操作
          _deleteActivityFromManagement(activity, controller);
        },
        child: Card(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Row(
              children: [
                // 左侧图片
                ClipRRect(
                  borderRadius: BorderRadius.circular(8.0),
                  child: CachedNetworkImage(
                    imageUrl: activity.activityImages.isNotEmpty 
                        ? activity.activityImages.first
                        : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png',
                    width: 80,
                    height: 80,
                    fit: BoxFit.cover,
                    errorWidget: (context, url, error) {
                      return Container(
                        width: 80,
                        height: 80,
                        color: Colors.grey[300],
                        child: const Icon(Icons.image_not_supported, size: 30),
                      );
                    },
                  ),
                ),
                const SizedBox(width: 12),
                // 中间信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题和标签
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              activity.activityTitle.isNotEmpty 
                                  ? activity.activityTitle 
                                  : '活动标题',
                              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              color: Colors.redAccent,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              activity.activityType.isNotEmpty 
                                  ? activity.activityType.first 
                                  : 'AA',
                              style: const TextStyle(color: Colors.white, fontSize: 10),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      // 活动详情
                      Text(
                        activity.activityDetails.isNotEmpty 
                            ? activity.activityDetails 
                            : '活动详情',
                        style: TextStyle(color: Colors.grey[600], fontSize: 12),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      // 当前人数
                      Text(
                        '当前人数 ${activity.activityCurrentParticipants}/${activity.activityMaxParticipants}',
                        style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.red, fontSize: 12),
                      ),
                    ],
                  ),
                ),
                // 右侧操作按钮和左滑提示
                Column(
                  children: [
                    // 管理按钮
                    GestureDetector(
                      onTap: () {
                        Get.to(() => ActivityManagementPage(
                          activityData: activity,
                        ));
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade50,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.person_outline, size: 14, color: Colors.blue.shade700),
                            const SizedBox(width: 4),
                            Text('管理', style: TextStyle(color: Colors.blue.shade700, fontSize: 12)),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    // 编辑按钮
                    GestureDetector(
                      onTap: () async {
                        final result = await Get.to(() => ActivityEditPage(
                          activityData: activity,
                        ));
                        
                        if (result == true) {
                          await Future.delayed(const Duration(milliseconds: 500));
                          controller.update();
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                        decoration: BoxDecoration(
                          color: Colors.green.shade50,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.edit_outlined, size: 14, color: Colors.green.shade700),
                            const SizedBox(width: 4),
                            Text('编辑', style: TextStyle(color: Colors.green.shade700, fontSize: 12)),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    // 🔥 添加左滑提示
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade100,
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.swipe_left, size: 10, color: Colors.grey.shade600),
                          const SizedBox(width: 2),
                          Text('左滑删除', style: TextStyle(color: Colors.grey.shade600, fontSize: 8)),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建真实评论卡片
  Widget _buildRealCommentCard(UserComment comment) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 16.0),
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        elevation: 2,
        child: Container(
          padding: const EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Row(
            children: [
              // 左侧图片
              ClipRRect(
                borderRadius: BorderRadius.circular(12.0),
                child: CachedNetworkImage(
                  imageUrl: comment.commentImages.isNotEmpty 
                      ? comment.commentImages.first
                      : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp',
                  width: 80,
                  height: 80,
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) {
                    return Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.circular(12.0),
                      ),
                      child: const Icon(Icons.image_not_supported, size: 40),
                    );
                  },
                ),
              ),
              const SizedBox(width: 16),
              
              // 右侧信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                      comment.commentTitle.isNotEmpty ? comment.commentTitle : '评论标题',
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 8),
                    
                    // 内容
                    Text(
                      comment.commentContent.isNotEmpty ? comment.commentContent : '评论内容',
                      style: TextStyle(
                        color: Colors.grey[700],
                        fontSize: 14,
                      ),
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              
              // 右侧操作区域
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  // 评论按钮
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Text(
                      '评论',
                      style: TextStyle(
                        color: Colors.grey.shade700,
                        fontSize: 12,
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  
                  // 删除按钮
                  GestureDetector(
                    onTap: () => _deleteRealComment(comment.commentId),
                    child: Container(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.delete_outline, size: 16, color: Colors.grey.shade600),
                          const SizedBox(width: 4),
                          Text('删除', style: TextStyle(color: Colors.grey.shade600, fontSize: 12)),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建真实参与活动卡片
  Widget _buildRealParticipantActivityCard(UserParticipatedActivity activity) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 16.0),
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        elevation: 2,
        child: Container(
          padding: const EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Row(
            children: [
              // 左侧图片
              ClipRRect(
                borderRadius: BorderRadius.circular(12.0),
                child: CachedNetworkImage(
                  imageUrl: activity.primaryImageUrl,
                  width: 80,
                  height: 80,
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) {
                    return Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.circular(12.0),
                      ),
                      child: const Icon(Icons.image_not_supported, size: 40),
                    );
                  },
                ),
              ),
              const SizedBox(width: 16),
              
              // 右侧信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题和标签
                    Row(
                      children: [
                        Text(
                          activity.activityTitle.isNotEmpty ? activity.activityTitle : '活动标题',
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                            color: Colors.black87,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            activity.paymentTypeText,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 6),
                    
                    // 描述
                    Text(
                      activity.activityDetails.isNotEmpty ? activity.activityDetails : '活动详情',
                      style: TextStyle(
                        color: Colors.grey[700],
                        fontSize: 14,
                      ),
                    ),
                    const SizedBox(height: 12),
                    
                    // 当前人数
                    RichText(
                      text: TextSpan(
                        style: const TextStyle(fontSize: 14, color: Colors.black87),
                        children: [
                          const TextSpan(text: '当前人数 '),
                          TextSpan(
                            text: '${activity.activityCurrentParticipants}',
                            style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              color: Colors.red,
                            ),
                          ),
                          TextSpan(
                            text: '/${activity.activityMaxParticipants}',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 14,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 删除真实评论
  void _deleteRealComment(int commentId) {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 72,
                height: 72,
                decoration: BoxDecoration(
                  color: Colors.red.withValues(alpha: 0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.delete_forever,
                  color: Colors.red,
                  size: 36,
                ),
              ),
              const SizedBox(height: 20),
              
              // 标题
              const Text(
                '删除评论',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 12),
              
              // 内容
              Text(
                '确定要删除这条评论吗？\\n删除后将无法恢复',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey.shade600,
                  height: 1.4,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 28),
              
              // 按钮
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Get.back(),
                      style: OutlinedButton.styleFrom(
                        side: BorderSide(color: Colors.grey.shade300),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          color: Colors.black54,
                          fontWeight: FontWeight.w500,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () async {
                        Get.back(); // 先关闭对话框
                        
                        // 调用删除评论API - 修复后按照MyApplication2格式
                        final controller = Get.find<PlaysController>();
                        final response = await CommentApi.deleteComment(
                          commentId: commentId,  // 只需要commentId参数
                        );
                        
                        if (response['status'] == 'success') {
                          ToastUtil.success('评论已删除');
                          // 刷新用户内容
                          await controller.refreshUserContent();
                        } else {
                          ToastUtil.error('删除失败: ${response['message'] ?? "未知错误"}');
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        elevation: 0,
                      ),
                      child: const Text(
                        '确定删除',
                        style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }



  /// 🔥 数据转换方法：将UserComment转换为PostModel用于详情页面显示（修复：使用发布者信息而非当前用户信息）
  PostModel _convertCommentToPostModel(UserComment comment) {
    try {
      developer.log('🔄 评论转换PostModel:');
      developer.log('   评论ID: ${comment.commentId}');
      developer.log('   发布者ID: ${comment.publisherId}');
      developer.log('   发布者昵称: ${comment.publisherNickname}');
      developer.log('   发布者头像: ${comment.publisherAvatar}');
      developer.log('   发布者签名: ${comment.publisherSignature}');
      developer.log('   标题: ${comment.commentTitle}');
      developer.log('   内容: ${comment.commentContent}');
      
      return PostModel(
        id: 'real_comment_${comment.commentId}', // 使用评论ID格式
        title: comment.commentTitle.isNotEmpty ? comment.commentTitle : '评论详情',
        content: comment.commentContent.isNotEmpty ? comment.commentContent : '暂无内容',
        images: comment.commentImages.isNotEmpty ? comment.commentImages : [], // 🔥 修复：只使用评论图片，不使用头像作为图片
        shoppingImages: comment.shoppingImages,
        authorName: comment.publisherNickname.isNotEmpty ? comment.publisherNickname : '评论作者', // 🔥 修复：使用发布者昵称
        authorAvatar: comment.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
        authorId: comment.publisherId, // 🔥 修复：使用发布者ID
        timeAgo: comment.commentPublishTime.isNotEmpty ? comment.commentPublishTime : '刚刚',
        likeCount: comment.likeCount,
        commentCount: comment.commentCount, // 🔥 使用评论的评论数量
        type: PostType.comment, // 🔥 必需参数
        authorSignature: comment.publisherSignature.isNotEmpty ? comment.publisherSignature : '来玩真的，不花假的', // 🔥 修复：使用发布者签名
        paymentType: '',
        location: comment.commentLocation.isNotEmpty ? comment.commentLocation : '',
        latitude: comment.latitude,
        longitude: comment.longitude,
        currentParticipants: null,
        maxParticipants: null,
        originalCommentId: comment.commentId, // 🔥 关键：保存原始评论ID用于API调用
      );
    } catch (e) {
      developer.log('❌ 评论数据转换失败: $e');
      // 🔥 修复：即使异常情况也使用发布者信息而非当前用户信息
      return PostModel(
        id: 'real_comment_${comment.commentId}',
        title: comment.commentTitle.isNotEmpty ? comment.commentTitle : '评论详情',
        content: comment.commentContent.isNotEmpty ? comment.commentContent : '暂无内容',
        images: comment.commentImages.isNotEmpty ? comment.commentImages : [], // 🔥 修复：使用评论图片
        shoppingImages: [],
        authorName: comment.publisherNickname.isNotEmpty ? comment.publisherNickname : '评论作者', // 🔥 修复：使用发布者昵称
        authorAvatar: comment.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
        authorId: comment.publisherId, // 🔥 修复：使用发布者ID
        timeAgo: comment.commentPublishTime.isNotEmpty ? comment.commentPublishTime : '刚刚',
        likeCount: comment.likeCount,
        commentCount: comment.commentCount, // 🔥 必需参数
        type: PostType.comment, // 🔥 必需参数
        authorSignature: comment.publisherSignature.isNotEmpty ? comment.publisherSignature : '来玩真的，不花假的', // 🔥 修复：使用发布者签名
        paymentType: '',
        location: comment.commentLocation.isNotEmpty ? comment.commentLocation : '',
        latitude: comment.latitude,
        longitude: comment.longitude,
        currentParticipants: null,
        maxParticipants: null,
        originalCommentId: comment.commentId,
      );
    }
  }

  /// 🔥 数据转换方法：将UserParticipatedActivity转换为PostModel用于详情页面显示
  PostModel _convertParticipatedActivityToPostModel(UserParticipatedActivity activity) {
    try {
      developer.log('🔄 参与活动转换PostModel:');
      developer.log('   活动ID: ${activity.activityId}');
      developer.log('   标题: ${activity.activityTitle}');
      
      return PostModel(
        id: 'real_activity_${activity.activityId}',
        title: activity.activityTitle.isNotEmpty ? activity.activityTitle : '参与的活动',
        content: activity.activityDetails.isNotEmpty ? activity.activityDetails : '暂无详情',
        images: activity.primaryImageUrl.isNotEmpty ? [activity.primaryImageUrl] : ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png'],
        shoppingImages: [],
        authorName: activity.publisherNickname.isNotEmpty ? activity.publisherNickname : '发布者',
        authorAvatar: activity.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
        authorId: activity.publisherId,
        timeAgo: '${activity.activityCurrentParticipants}/${activity.activityMaxParticipants}人',
        likeCount: 0,
        commentCount: activity.activityCurrentParticipants, // 🔥 必需参数 - 使用当前参与人数
        type: PostType.activity, // 🔥 必需参数
        authorSignature: activity.publisherSignature.isNotEmpty ? activity.publisherSignature : '来玩真的，不花假的', // 🔥 修复：使用发布者真实签名
        paymentType: activity.paymentTypeText.isNotEmpty ? activity.paymentTypeText : 'AA',
        publishTime: activity.activityPublishTime, // 🔥 传递真实的发布时间
        location: activity.activityLocation.isNotEmpty ? activity.activityLocation : '',
        latitude: null,
        longitude: null,
        currentParticipants: activity.activityCurrentParticipants,
        maxParticipants: activity.activityMaxParticipants,
      );
    } catch (e) {
      developer.log('❌ 参与活动数据转换失败: $e');
      return PostModel(
        id: 'real_activity_${activity.activityId}',
        title: '参与的活动',
        content: '暂无详情',
        images: ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png'],
        shoppingImages: [],
        authorName: activity.publisherNickname.isNotEmpty ? activity.publisherNickname : '发布者',
        authorAvatar: activity.publisherAvatar, // 🔥 修复：直接使用发布者头像，不使用默认头像
        authorId: activity.publisherId,
        timeAgo: '参与的活动',
        likeCount: 0,
        commentCount: 0, // 🔥 必需参数
        type: PostType.activity, // 🔥 必需参数
        authorSignature: activity.publisherSignature.isNotEmpty ? activity.publisherSignature : '来玩真的，不花假的', // 🔥 修复：使用发布者真实签名
        paymentType: 'AA',
        publishTime: activity.activityPublishTime, // 🔥 即使异常情况也尝试保持时间信息
        location: '',
        latitude: null,
        longitude: null,
        currentParticipants: 0,
        maxParticipants: 999,
      );
    }
  }



  /// 🔥 显示评论详情
  void _showCommentDetail(UserComment comment) {
    try {
      developer.log('📱 点击评论，显示详情: ${comment.commentTitle}');
      
      // 转换数据格式
      final postModel = _convertCommentToPostModel(comment);
      
      // 显示评论详情底部弹窗
      ReviewDetailBottomSheet.show(
        post: postModel,
      );
      
      developer.log('✅ 评论详情页面已显示');
    } catch (e) {
      developer.log('❌ 显示评论详情失败: $e');
      ToastUtil.error('显示详情失败');
    }
  }

  /// 🔥 显示参与活动详情 - 与MyApplication2保持一致，发送API请求
  void _showParticipatedActivityDetail(UserParticipatedActivity activity) async {
    try {
      developer.log('📱 点击参与活动，显示详情: ${activity.activityTitle}');
      developer.log('🔄 与MyApplication2保持一致，发送活动详情API请求');
      
      // 🔥 与MyApplication2保持一致：发送活动详情API请求而不是直接使用列表数据
      final currentUser = UserService.to.currentUser;
      
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      developer.log('🚀 开始获取参与活动完整详情');
      developer.log('📝 活动ID: ${activity.activityId}');
      developer.log('👤 用户ID: ${currentUser.userid}');
      
      // 🔥 调用活动详情API（与MyApplication2和历史活动保持一致）
      final response = await ActivityApi.getActivityDetail(
        activityId: activity.activityId,
      );
      
      if (response['status'] == 'success' && response['activity'] != null) {
        final activityDetailJson = response['activity'] as Map<String, dynamic>;
        // 🔥 转换为ActivityData对象
        final activityDetail = ActivityData.fromJson(activityDetailJson);
        developer.log('✅ 参与活动详情获取成功');
        developer.log('📊 发布者头像: "${activityDetail.publisherAvatar}"');
        developer.log('📊 发布者昵称: ${activityDetail.publisherNickname}');
        
        // 🔥 使用API返回的完整数据创建PostModel
        final postModel = PostModel(
          id: 'participated_activity_${activityDetail.activityId}',
          title: activityDetail.activityTitle.isNotEmpty ? activityDetail.activityTitle : '参与活动',
          content: activityDetail.activityDetails.isNotEmpty ? activityDetail.activityDetails : '暂无详情',
          images: activityDetail.activityImages.isNotEmpty ? activityDetail.activityImages : ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png'],
          shoppingImages: [],
          authorName: activityDetail.publisherNickname.isNotEmpty ? activityDetail.publisherNickname : '发布者',
          authorAvatar: activityDetail.publisherAvatar, // 🔥 使用API返回的完整发布者头像数据
          authorId: activityDetail.publisherId,
          timeAgo: '${activityDetail.activityCurrentParticipants}/${activityDetail.activityMaxParticipants}人',
          likeCount: 0,
          commentCount: activityDetail.activityCurrentParticipants,
          type: PostType.activity,
          authorSignature: activityDetail.publisherSignature.isNotEmpty ? activityDetail.publisherSignature : '来玩真的，不花假的',
          paymentType: activityDetail.activityType.isNotEmpty ? activityDetail.activityType.first : 'AA',
          publishTime: activityDetail.activityPublishTime,
          location: activityDetail.activityLocation,
          latitude: activityDetail.latitude,
          longitude: activityDetail.longitude,
          currentParticipants: activityDetail.activityCurrentParticipants,
          maxParticipants: activityDetail.activityMaxParticipants,
        );
        
        // 显示活动详情底部弹窗
        ActivityDetailBottomSheet.show(
          activity: postModel,
          onJoinSuccess: () {
            developer.log('🎉 参与活动详情操作完成');
          },
        );
        
        developer.log('✅ 参与活动详情页面已显示（使用API完整数据）');
      } else {
        developer.log('❌ 参与活动详情获取失败: ${response['message'] ?? "未知错误"}');
        
        // 🎯 API失败时兜底：使用列表数据（但记录日志）
        developer.log('🔄 API失败，使用列表数据作为兜底方案');
        final postModel = _convertParticipatedActivityToPostModel(activity);
        
        ActivityDetailBottomSheet.show(
          activity: postModel,
          onJoinSuccess: () {
            developer.log('🎉 参与活动详情操作完成（兜底方案）');
          },
        );
        
        ToastUtil.warning('使用缓存数据显示，头像可能不完整');
      }
    } catch (e) {
      developer.log('❌ 显示参与活动详情异常: $e');
      ToastUtil.error('显示详情失败: $e');
    }
  }



  /// 🔥 新增：显示历史活动详情（从ActivityData）- 与MyApplication2保持一致，发送API请求
  void _showHistoricalActivityDetailFromActivityData(ActivityData activity) async {
    try {
      developer.log('📱 点击历史活动，显示详情: ${activity.activityTitle}');
      developer.log('🔄 与MyApplication2保持一致，发送活动详情API请求');
      
      // 🔥 与MyApplication2保持一致：发送活动详情API请求而不是直接使用列表数据
      final currentUser = UserService.to.currentUser;
      
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      developer.log('🚀 开始获取历史活动完整详情');
      developer.log('📝 活动ID: ${activity.activityId}');
      developer.log('👤 用户ID: ${currentUser.userid}');
      
      // 🔥 调用活动详情API（与MyApplication2保持一致）
      final response = await ActivityApi.getActivityDetail(
        activityId: activity.activityId,
      );
      
      if (response['status'] == 'success' && response['activity'] != null) {
        final activityDetailJson = response['activity'] as Map<String, dynamic>;
        // 🔥 转换为ActivityData对象
        final activityDetail = ActivityData.fromJson(activityDetailJson);
        developer.log('✅ 活动详情获取成功');
        developer.log('📊 发布者头像: "${activityDetail.publisherAvatar}"');
        developer.log('📊 发布者昵称: ${activityDetail.publisherNickname}');
        
        // 🔥 使用API返回的完整数据创建PostModel
        final postModel = PostModel(
          id: 'ended_activity_${activityDetail.activityId}',
          title: activityDetail.activityTitle.isNotEmpty ? activityDetail.activityTitle : '历史活动',
          content: activityDetail.activityDetails.isNotEmpty ? activityDetail.activityDetails : '暂无详情',
          images: activityDetail.activityImages.isNotEmpty ? activityDetail.activityImages : ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png'],
          shoppingImages: [],
          authorName: activityDetail.publisherNickname.isNotEmpty ? activityDetail.publisherNickname : '发布者',
          authorAvatar: activityDetail.publisherAvatar, // 🔥 使用API返回的完整发布者头像数据
          authorId: activityDetail.publisherId,
          timeAgo: activityDetail.activityPublishTime.isNotEmpty ? activityDetail.activityPublishTime : '历史活动',
          likeCount: 0,
          commentCount: activityDetail.activityCurrentParticipants,
          type: PostType.activity,
          authorSignature: activityDetail.publisherSignature.isNotEmpty ? activityDetail.publisherSignature : '来玩真的，不花假的',
          paymentType: activityDetail.activityType.isNotEmpty ? activityDetail.activityType.first : 'AA',
          publishTime: activityDetail.activityPublishTime,
          location: activityDetail.activityLocation,
          latitude: activityDetail.latitude,
          longitude: activityDetail.longitude,
          currentParticipants: activityDetail.activityCurrentParticipants,
          maxParticipants: activityDetail.activityMaxParticipants,
        );
        
        // 显示活动详情底部弹窗
        ActivityDetailBottomSheet.show(
          activity: postModel,
          onJoinSuccess: () {
            developer.log('🎉 历史活动详情操作完成');
          },
        );
        
        developer.log('✅ 历史活动详情页面已显示（使用API完整数据）');
      } else {
        developer.log('❌ 活动详情获取失败: ${response['message'] ?? "未知错误"}');
        
        // 🎯 API失败时兜底：使用列表数据（但记录日志）
        developer.log('🔄 API失败，使用列表数据作为兜底方案');
        final postModel = PostModel(
          id: 'ended_activity_${activity.activityId}',
          title: activity.activityTitle.isNotEmpty ? activity.activityTitle : '历史活动',
          content: activity.activityDetails.isNotEmpty ? activity.activityDetails : '暂无详情',
          images: activity.activityImages.isNotEmpty ? activity.activityImages : ['https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_dbbd0aa66f4e22dd88e386835e890715_edit_391764026560533.png'],
          shoppingImages: [],
          authorName: activity.publisherNickname.isNotEmpty ? activity.publisherNickname : '发布者',
          authorAvatar: activity.publisherAvatar.isNotEmpty ? activity.publisherAvatar : '', // 列表数据可能为空
          authorId: activity.publisherId,
          timeAgo: activity.activityPublishTime.isNotEmpty ? activity.activityPublishTime : '历史活动',
          likeCount: 0,
          commentCount: activity.activityCurrentParticipants,
          type: PostType.activity,
          authorSignature: activity.publisherSignature.isNotEmpty ? activity.publisherSignature : '来玩真的，不花假的',
          paymentType: activity.activityType.isNotEmpty ? activity.activityType.first : 'AA',
          publishTime: activity.activityPublishTime,
          location: activity.activityLocation,
          latitude: activity.latitude,
          longitude: activity.longitude,
          currentParticipants: activity.activityCurrentParticipants,
          maxParticipants: activity.activityMaxParticipants,
        );
        
        ActivityDetailBottomSheet.show(
          activity: postModel,
          onJoinSuccess: () {
            developer.log('🎉 历史活动详情操作完成（兜底方案）');
          },
        );
        
        ToastUtil.warning('使用缓存数据显示，头像可能不完整');
      }
    } catch (e) {
      developer.log('❌ 显示历史活动详情异常: $e');
      ToastUtil.error('显示详情失败: $e');
    }
  }

  /// 🔥 新增：显示删除活动确认对话框
  Future<bool?> _showDeleteActivityConfirmDialog(ActivityData activity) async {
    return await Get.dialog<bool>(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 72,
                height: 72,
                decoration: BoxDecoration(
                  color: Colors.red.withValues(alpha: 0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.delete_forever,
                  color: Colors.red,
                  size: 36,
                ),
              ),
              const SizedBox(height: 20),
              
              // 标题
              const Text(
                '删除活动',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 12),
              
              // 活动信息
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey.shade50,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  children: [
                    Text(
                      activity.activityTitle.isNotEmpty ? activity.activityTitle : '活动标题',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '当前参与人数: ${activity.activityCurrentParticipants}',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey.shade600,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              
              // 内容
              Text(
                '确定要删除这个活动吗？\n删除后将无法恢复，参与者也会收到通知',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey.shade600,
                  height: 1.4,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 28),
              
              // 按钮
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Get.back(result: false),
                      style: OutlinedButton.styleFrom(
                        side: BorderSide(color: Colors.grey.shade300),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          color: Colors.black54,
                          fontWeight: FontWeight.w500,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () => Get.back(result: true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        elevation: 0,
                      ),
                      child: const Text(
                        '确定删除',
                        style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 🔥 新增：从活动管理列表中删除活动
  void _deleteActivityFromManagement(ActivityData activity, PlaysController controller) async {
    try {
      developer.log('🗑️ 开始删除活动管理中的活动，ID: ${activity.activityId}');
      
      // 显示加载提示
      ToastUtil.info('正在删除活动...');
      
      // 🔥 使用活动删除API（与MyApplication2一致）
      final response = await ActivityApi.deleteActivity(
        activityId: activity.activityId,
        userId: controller.currentUserId.value, // 🔑 添加用户ID验证
      );
      
      if (response['success'] == true || response['status'] == 'success') {
        ToastUtil.success('活动已删除');
        
        // 🎯 立即从列表中移除已删除的活动
        controller.myActivities.removeWhere((item) => item.activityId == activity.activityId);
        
        // 刷新用户内容数据
        await controller.refreshUserContent();
        
        // 强制更新UI
        controller.update();
        
        developer.log('✅ 活动管理删除成功');
      } else {
        ToastUtil.error('删除失败: ${response['message'] ?? "未知错误"}');
        developer.log('❌ 活动管理删除失败: ${response['message']}');
      }
    } catch (e) {
      developer.log('💥 删除活动管理中的活动异常: $e');
      ToastUtil.error('删除失败: $e');
    }
  }

  /// 🔥 新增：使用正确的API删除历史活动（与MyApplication2一致）
  void _deleteHistoricalActivityWithCorrectAPI(int activityId, int index) {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: Container(
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 图标
              Container(
                width: 72,
                height: 72,
                decoration: BoxDecoration(
                  color: Colors.red.withValues(alpha: 0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.history_toggle_off,
                  color: Colors.red,
                  size: 36,
                ),
              ),
              const SizedBox(height: 20),
              
              // 标题
              const Text(
                '删除历史活动',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 12),
              
              // 内容
              Text(
                '确定要删除这个历史活动吗？\\n删除后将无法恢复',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey.shade600,
                  height: 1.4,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 28),
              
              // 按钮
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Get.back(),
                      style: OutlinedButton.styleFrom(
                        side: BorderSide(color: Colors.grey.shade300),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          color: Colors.black54,
                          fontWeight: FontWeight.w500,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () async {
                        Get.back(); // 先关闭对话框
                        
                        try {
                          // 🎯 使用与MyApplication2一致的删除格式
                          developer.log('🗑️ 开始删除历史活动，ID: $activityId');
                          
                          // 显示加载提示
                          ToastUtil.info('正在删除活动...');
                          
                          // 🔥 修复：使用正确的删除API格式（与MyApplication2一致）
                          final controller = Get.find<PlaysController>();
                          final response = await ActivityApi.deleteActivity(
                            activityId: activityId,
                            userId: controller.currentUserId.value, // 🔑 添加用户ID验证
                          );
                          
                          if (response['success'] == true || response['status'] == 'success') {
                            ToastUtil.success('历史活动已删除');
                            
                            // 🎯 立即从列表中移除已删除的活动
                            final controller = Get.find<PlaysController>();
                            controller.myEndedActivities.removeAt(index);
                            
                            // 刷新用户内容数据
                            await controller.refreshUserContent();
                            
                            // 强制更新UI
                            controller.update();
                            
                            developer.log('✅ 历史活动删除成功');
                          } else {
                            ToastUtil.error('删除失败: ${response['message'] ?? "未知错误"}');
                            developer.log('❌ 历史活动删除失败: ${response['message']}');
                          }
                        } catch (e) {
                          developer.log('💥 删除历史活动异常: $e');
                          ToastUtil.error('删除失败: $e');
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        elevation: 0,
                      ),
                      child: const Text(
                        '确定删除',
                        style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
